package com.haohan.cloud.scm.goods.core.impl;

import cn.hutool.core.util.StrUtil;
import com.haohan.cloud.scm.api.goods.entity.Goods;
import com.haohan.cloud.scm.api.goods.entity.GoodsCollections;
import com.haohan.cloud.scm.api.manage.entity.Merchant;
import com.haohan.cloud.scm.common.tools.exception.ErrorDataException;
import com.haohan.cloud.scm.goods.core.GoodsCollectionsCoreService;
import com.haohan.cloud.scm.goods.service.GoodsCollectionsService;
import com.haohan.cloud.scm.goods.service.GoodsService;
import com.haohan.cloud.scm.goods.utils.ScmGoodsUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @author dy
 * @date 2020/5/27
 */
@Service
@AllArgsConstructor
public class GoodsCollectionsCoreServiceImpl implements GoodsCollectionsCoreService {

    private final GoodsCollectionsService goodsCollectionsService;
    private final GoodsService goodsService;
    private final ScmGoodsUtils scmGoodsUtils;

    @Override
    public boolean addCollections(String uid, String goodsId) {
        if (StrUtil.isBlank(uid) || StrUtil.isBlank(goodsId)) {
            throw new ErrorDataException("缺少参数uid、goodsId");
        }
        GoodsCollections exist = goodsCollectionsService.fetchCollections(uid, goodsId);
        if (null != exist) {
            return true;
        }
        Goods goods = goodsService.getById(goodsId);
        if (null == goods) {
            throw new ErrorDataException("商品id有误");
        }
        // 原系统使用平台商家
        Merchant pm = scmGoodsUtils.fetchPlatformMerchant();
        GoodsCollections goodsCollections = new GoodsCollections();
        goodsCollections.setUid(uid);
        goodsCollections.setGoodsId(goodsId);
        goodsCollections.setPmId(pm.getId());
        return goodsCollectionsService.save(goodsCollections);
    }

    @Override
    public boolean removeCollections(String uid, String goodsId) {
        GoodsCollections exist = goodsCollectionsService.fetchCollections(uid, goodsId);
        if (null == exist) {
            return true;
        }
        return goodsCollectionsService.removeById(exist.getId());
    }
}
